<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-05-12 16:47:51
-->
<template>
  <BaseDialog v-model="dialogVisible" :title="title" width="900px" :before-close="handleClose" :max-height="600">
    <el-descriptions v-loading="viewLoading" :column="2" border :label-width="140">
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.groupPeriodCode') }}</template>
        {{ formData.code || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.groupPeriodName') }}</template>
        {{ formData.name || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.routeName') }}</template>
        {{ formData.routeName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.departureDate') }}</template>
        {{ g_dayjs(formData.startTime).format('YYYY-MM-DD HH:mm:ss') || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.weekday') }}</template>
        <span>{{
          g_options.getOptionText(
          g_options.dateDayOptions,
          g_dayjs(formData.startTime).day(),
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.groupPeriodType') }}</template>
        <span>{{
          g_options.getOptionText(
          g_options.groupPeriodTypeOptions,
          formData.type,
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('hotel.customer') }}</template>
        {{ formData.customerName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.plannedNumber') }}</template>
        {{ g_utils.formatValue(formData.peopleCountPlan) }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.currentNumber') }}</template>
        {{ g_utils.formatValue(formData.peopleCountReal) }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.remainingSeats') }}</template>
        {{
        g_utils.formatValue(
        formData.peopleCountPlan - formData.peopleCountReal
        )
        }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.groupCreator') }}</template>
        {{ formData.createUser || '--' }}
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.routeType') }}</template>
        <span>{{
          g_options.getOptionText(
          g_options.routeTypeOptions,
          formData.routeType,
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('public.status') }}</template>
        <span class="dot-status" :class="
            g_options.getOptionText(
              g_options.tourDateStatusOptions,
              formData.status,
              '--',
              'class'
            )
          ">{{
          g_options.getOptionText(
          g_options.tourDateStatusOptions,
          formData.status,
          '--'
          )
          }}</span>
      </el-descriptions-item>
      <el-descriptions-item width="200">
        <template #label>{{ $t('travelAgency.groupPeriodDesc') }}</template>
        {{ formData.note || '--' }}
      </el-descriptions-item>
    </el-descriptions>
    <el-form ref="refDialogForm" v-loading="formLoading" :label-width="language === 'en' ? '180px' : '80px'"
      :model="tripFormData" style="margin-top: 10px">
      <div class="tabs-container">
        <el-tabs v-model="tabValue" style="flex: 1" @tab-change="handleTabChange">
          <el-tab-pane v-for="item in g_options.lineTypeOptions" :key="item.value" :name="item.value"
            :label="item.label" class="tab_item">
            <el-form-item :label="$t('travelAgency.description')" prop="fileContent"
              v-if="item.value!=='8'&&item.value!=='3'">
              <TextInput v-model="tripFormData.fileContent[item.value].remark" type="textarea" clearable :rows="5"
                placeholder="无" disabled :label="$t('travelAgency.description')" />
            </el-form-item>
            <div v-if="item.value==='3'">
              <BaseTable ref="refTravelTable" :data="formData.tripList" row-key="id" style="margin: 10px 0">
                <TableColumn :label="$t('fleet.departure')" class="ignore">
                  <TableColumn prop="startRegionCode" :label="$t('public.region')"
                    :column-width="travelColumnWidth.startRegionCode">
                    <template #default="{ row }">
                      <span>{{ g_utils.getRegionName(row.startRegionCode) }}</span>
                    </template>
                  </TableColumn>
                  <TableColumn prop="startAddress" :label="$t('public.detailAddress')"
                    :column-width="travelColumnWidth.startAddress" />
                </TableColumn>
                <TableColumn :label="$t('fleet.destination')" class="ignore">
                  <TableColumn prop="endRegionCode" :label="$t('public.region')"
                    :column-width="travelColumnWidth.endRegionCode">
                    <template #default="{ row }">
                      <span>{{ g_utils.getRegionName(row.endRegionCode) }}</span>
                    </template>
                  </TableColumn>
                  <TableColumn prop="endAddress" :label="$t('public.detailAddress')"
                    :column-width="travelColumnWidth.endAddress" />
                </TableColumn>
                <TableColumn prop="startTime" :label="$t('fleet.departureTime')"
                  :column-width="travelColumnWidth.startTime" />
                <TableColumn prop="endTime" :label="$t('public.endTime')" :column-width="travelColumnWidth.endTime" />
                <TableColumn prop="through" :label="$t('fleet.passingScenery')"
                  :column-width="travelColumnWidth.through" />
              </BaseTable>
            </div>
            <div v-if="item.value==='8'">
              <el-table :data="totleTable" style="width: 100%;margin-top: 10px;" border v-if="totleTable.length"
                class="total_excel" :span-method="handleSpanMethod">
                <el-table-column prop="tripDate" :label="$t('travelAgency.date')" width="100" align="center" />
                <el-table-column prop="tripDay" :label="$t('travelAgency.tripDay')" width="70" align="center" />
                <el-table-column prop="trip" width="210" :label="$t('travelAgency.trip')" align="center" />
                <el-table-column prop="type" width="60" :label="$t('travelAgency.type')"
                  align="center"></el-table-column>
                <el-table-column prop="content" :label="$t('travelAgency.resource')" align="center"></el-table-column>
              </el-table>
              <el-empty :description="$t('travelAgency.noData')" v-else />
            </div>
            <div v-if="tripFormData.fileContent[item.value] && tripFormData.fileContent[item.value].fileId">
              <el-button text @click="handleDownload(item)">{{ $t('travelAgency.downloadFile') }}</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
    <template #footer>
      <div class="detail-dialog-footer">
        <el-button plain @click="handleClose" v-if="type === 'confirm'">{{
          $t('public.close')
          }}</el-button>
        <el-button v-if="type === 'confirm'" plain type="primary" @click="handleConfirm">{{ $t('public.confirm')
          }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const formData = ref({})
const props = defineProps({
  type: {
    type: String,
    default: 'view' // view | confirm
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const title = computed(() =>
  props.type === 'confirm'
    ? g_t('travelAgency.groupPeriodConfirm')
    : g_t('public.detail')
)
const viewLoading = ref(false)
const formLoading = ref(false)

const refDialogForm = ref(null)
const tabValue = ref(g_options.lineTypeOptions[0].value)
const fileContent = Object.fromEntries(
  g_options.lineTypeOptions.map(item => [
    item.value,
    { fileId: '', remark: '' }
  ])
)

const tripFormData = ref({
  fileId: '',
  fileContent: g_.cloneDeep(fileContent)
})

const tripList = ref([])
const totleTable = ref([])
const refTravelTable = ref(null)
const travelColumnWidth = ref({})

const handleTabChange = e => {
  if (!tripFormData.value.fileContent[e].updateStatus && tabValue.value !== '8') {
    getRouteResourceQuery()
  }
  refDialogForm.value.validateField(['fileContent'])
}


const getRouteResourceQuery = () => {
  formLoading.value = true
  g_api.travelAgency
    .apiTeamRouteResourceQuery({
      type: tabValue.value,
      teamId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        tripFormData.value.fileContent[tabValue.value] = {
          ...data,
          updateStatus: true
        }
      }
    })
    .finally(_ => {
      formLoading.value = false
    })
}

const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 日期、天数、行程列需要合并，每7行合并为1行
  if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
    // 每7行的第一个行显示合并，其余6行隐藏
    if (rowIndex % 7 === 0) {
      return {
        rowspan: 7,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }

  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

watch(
  () => tripList.value,
  nv => {
    nextTick(() => {
      useTableColumnWidth({
        refTable: refTravelTable.value
      }).getTableColumnWidth(data => {
        travelColumnWidth.value = data
      })
    })
  },
  {
    // immediate: true,
    deep: true
  }
)

onMounted(() => {
  getFormData()
  getRouteResourceQuery()
})

// 查询数据
const getFormData = () => {
  viewLoading.value = true
  g_api.travelAgency
    .apiTeamDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = data
        tripList.value = data.tripList || []
        // 转换数据格式
        if (data.routeResourceTotals && data.routeResourceTotals.length > 0) {
          const convertedData = []
          data.routeResourceTotals.forEach(item => {
            // 根据7个类型转换为7条数据
            const types = [
              { type: g_t('travelAgency.meal'), key: 'meal' },
              { type: g_t('travelAgency.hotel'), key: 'hotel' },
              { type: g_t('travelAgency.car'), key: 'car' },
              { type: g_t('travelAgency.play'), key: 'play' },
              { type: g_t('travelAgency.shop'), key: 'shop' },
              { type: g_t('travelAgency.enjoy'), key: 'enjoy' },
              { type: g_t('travelAgency.other'), key: 'other' }
            ]

            types.forEach(typeInfo => {
              convertedData.push({
                tripDate: item.tripDate,
                tripDay: item.tripDay,
                trip: item.trip,
                type: typeInfo.type,
                content: item[typeInfo.key] || g_t('travelAgency.none'),
                routeId: item.routeId,
                tenantId: item.tenantId,
                id: item.id,
                rowId: item.rowId
              })
            })
          })
          totleTable.value = convertedData
        } else {
          totleTable.value = []
        }
      }
    })
    .finally(_ => {
      viewLoading.value = false
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleDownload = item => {
  const { fileId, fileName } = tripFormData.value.fileContent[item.value]
  g_api.travelAgency
    .apiFileDownload({
      fileId
    })
    .then(res => {
      if (res.code === '200' && res.data) {
        // window.open(res.data)
        g_utils.downloadFile(res.data, fileName)
      }
    })
    .finally(() => { })
}

const handleConfirm = () => {
  g_api.travelAgency
    .apiTeamUpdateStatus({
      id: props.id,
      status: 3
    })
    .then(res => {
      if (res.code === '200') {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        handleClose()
        emit('update')
      }
    })
}
</script>

<style>
.total_excel th.el-table__cell {
  background-color: transparent !important;
  font-size: 14px !important;
}


.total_excel {
  &.el-table {
    border: 1px solid #000;

    td,
    th {
      border-right: 1px solid #000;
      border-bottom: 1px solid #000;
    }

    th.el-table__cell.is-leaf {
      border-bottom: 1px solid #000;
    }

    &::before {
      background-color: #000;
      height: 1px;
    }
  }
}
</style>
<style scoped lang="scss">
.tabs-container {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .tab_item {
    min-height: 350px;
    max-height: 400px;
    padding-top: 10px;
    overflow-y: auto;
  }

  :deep(.el-tabs__nav.is-top) {
    width: 100%;
    justify-content: space-around;
  }
}

.detail-dialog-footer {
  text-align: right;
}
</style>